﻿using ATHTaskList2012.Entities;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ATHTaskList2012.Models.Data
{
    public class NHibernateHelper
    {
        private const string CurrentSessionKey = "nhibernate.current_session";

        private static ISessionFactory _sessionFactory;

        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                    InitializeSessionFactory();

                return _sessionFactory;
            }
        }

        private static void InitializeSessionFactory()
        {
            _sessionFactory = Fluently.Configure()
              .Database(
                SQLiteConfiguration.Standard
                  .UsingFile("athtasklist.db")
              )
              .Mappings(m =>
                m.FluentMappings.AddFromAssemblyOf<User>())
                .ExposeConfiguration(c =>
                {
                    BuildSchema(c);
                    c.SetProperty("current_session_context_class", "thread_static");
                })
              .BuildSessionFactory();
        }

        public static ISession GetCurrentSession()
        {
            ISession currentSession = null;
            HttpContext context = HttpContext.Current;
            if (context != null)
            {
                currentSession = context.Items[CurrentSessionKey] as ISession;
            }
            if (currentSession == null)
            {
                lock (_sessionFactory)
                {
                    currentSession = _sessionFactory.OpenSession();
                }
            }
            if (context != null)
            {
                context.Items[CurrentSessionKey] = currentSession;
            }

            return currentSession;
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }

        private static void BuildSchema(Configuration cfg)
        {
            //new SchemaExport(cfg).Create(false, true);
            new SchemaUpdate(cfg);
        }
    }
}